package com.chcit.mobile.mvp.common.presenter;

import android.app.Application;
import android.util.SparseArray;

import com.chcit.mobile.R;
import com.chcit.mobile.common.HttpMethodContains;
import com.chcit.mobile.common.SPDErrorHandle;
import com.chcit.mobile.mvp.common.contract.HomeContract;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.entity.ChildrenBean;
import com.chcit.mobile.mvp.entity.HomeItem;
import com.chcit.mobile.mvp.home.HomeAdapter;
import com.chcit.mobile.mvp.entity.TaskMenuBean;
import com.chcit.mobile.mvp.receive.fragment.PurchaseOldReceiveFragment;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;

import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;


@ActivityScope
public class HomePresenter extends BasePresenter<HomeContract.Model, HomeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    @Inject
    HomeAdapter mAdapter;

    SparseArray<HomeItem> mHomeItemIndexs = new SparseArray<>();

    @Inject
    public HomePresenter(HomeContract.Model model, HomeContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        mAdapter = null;

    }

    public void getMenues(){
        mModel.getMenues().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .doFinally(()->{
                    mRootView.hideLoading();
                })
                .subscribe(new SPDErrorHandle<List<ChildrenBean>>(mErrorHandler){

                    @Override
                    public void onNext( List<ChildrenBean> menuBeans) {

                        for (int i = 0; i < menuBeans.size(); i++) {
                            ChildrenBean childrenBean = menuBeans.get(i);
                            HomeItem item = new HomeItem();
                            item.setTitle(childrenBean.getText());
                            String ItemClass = childrenBean.getUrl();
                            Class<?> delegate = PurchaseOldReceiveFragment.class;
                            int imageResource =  R.drawable.svg_menu;
                            MenuTypeEnum menuTypeEnum = MenuTypeEnum.getAllClazz().get(ItemClass);
                            if(menuTypeEnum == null){
                                menuTypeEnum = MenuTypeEnum.getAllClazz().get(childrenBean.getId());
                            }
                            if(menuTypeEnum != null){
                                delegate = menuTypeEnum.getClazz();
                                imageResource = menuTypeEnum.getImageResource();
                                menuTypeEnum.setDesc(childrenBean.getText());
                                item.setId(childrenBean.getId());
                                item.setActivity(delegate);
                                item.setImageResource(imageResource);
                                item.setUrl(Quick.getConfiguration(ConfigKeys.API_HOST)+HttpMethodContains.IMAGE_URL+childrenBean.getIcon());
                                mHomeItemIndexs.put(menuTypeEnum.getIndex(),item);
                                mAdapter.addData(item);
                            }
                        }
//                        if(BuildConfig.DEBUG){
//                            HomeItem item = new HomeItem();
//                            item.setActivity(ReceiveBindSearchFragment.class);
//                            item.setImageResource(R.drawable.svg_menu);
//                            item.setTitle("测试");
//                            mHomeItems.add(item);
//                        }
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }


    public void queryWaitTask(){
        mModel.getTaskMenues()
                .map(this::parseTask)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SPDErrorHandle<List<TaskMenuBean>>(mErrorHandler){
                    @Override
                    public void onNext(List<TaskMenuBean> result) {

                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

    @NotNull
    private List<TaskMenuBean> parseTask(List<TaskMenuBean> result) {
        for(int i=0;i<mHomeItemIndexs.size();i++){
            HomeItem item = mHomeItemIndexs.valueAt(i);
            item.setTaskNumber(0);
        }
        for(TaskMenuBean tmb: result){
            switch (tmb.getMenu().getId()){
                case "spd.web.w1.wms.poReceive":
                    HomeItem k = mHomeItemIndexs.get(2);
                    if(k != null){
                        k.setTaskNumber(tmb.getCount());
                    }
                    continue;

                case "spd.web.w1.wms.poCheck":
                     k = mHomeItemIndexs.get(0);
                    if(k != null){
                       k.setTaskNumber(tmb.getCount());
                    }
                    continue;
                case "spd.web.w1.wms.prShipment":
                     k = mHomeItemIndexs.get(6);
                    if(k!= null){
                       k.setTaskNumber(tmb.getCount());
                    }
                    continue;
                case "spd.web.w1.output.asnRejectReceive":
                     k = mHomeItemIndexs.get(5);
                    if(k!= null){
                        k.setTaskNumber(tmb.getCount());
                    }
                   break;
            }
        }
        return  result;
    }

    CompositeDisposable compositeDisposable = new CompositeDisposable();

    public void start() {
        compositeDisposable.dispose();
        compositeDisposable = new CompositeDisposable();

        //loopAtFixRate();
        //loopAtFixRateEx();
        loopSequence();
    }
    // 嵌套风格loop， 不管实际结果，反正到点了就执行。
    private void loopAtFixRate() {
        compositeDisposable.add(Observable.interval(0, 500, TimeUnit.SECONDS)
                .subscribe(aLong -> queryWaitTask()));
    }

    // 按照顺序loop，意味着第一次结果请求完成后，再考虑下次请求
    private void loopSequence() {
        Disposable disposable = getDataFromServer()
                .doOnSubscribe(disposable1 -> {

                })
                .doOnError(throwable -> {
                    mRootView.showMessage(throwable.getMessage());
                })
                .delay(300, TimeUnit.SECONDS, true)       // 设置delayError为true，表示出现错误的时候也需要延迟5s进行通知，达到无论是请求正常还是请求失败，都是5s后重新订阅，即重新请求。
                .subscribeOn(Schedulers.io())
                .repeat()   // repeat保证请求成功后能够重新订阅。
                .retry()    // retry保证请求失败后能重新订阅
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> mAdapter.notifyDataSetChanged(), throwable -> mRootView.showMessage(throwable.getMessage()));
        compositeDisposable.add(disposable);
    }

    private Observable<List<TaskMenuBean>> getDataFromServer() {

       return mModel.getTaskMenues()
                .map(this::parseTask);



    }


    public void stop() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

}
